const app = getApp();

Page({
  data: {
    list: []
  },

  onLoad() {
    this.loadList();
  },

  onPullDownRefresh() {
    this.loadList(() => {
      wx.stopPullDownRefresh();
    });
  },

  loadList(callback) {
    wx.showLoading({ title: '加载中...' });
    
    wx.request({
      url: app.globalData.baseUrl + '/getQualityStandards',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.data.code === 1) {
          const list = res.data.data || [];
          
          // 格式化数据
          list.forEach(item => {
            item.createtime_text = this.formatTime(item.createtime);
            // 计算检查项数量
            if (item.check_items_array) {
              let count = 0;
              for (let category in item.check_items_array) {
                count += Object.keys(item.check_items_array[category]).length;
              }
              item.check_items_count = count;
            } else {
              item.check_items_count = 0;
            }
          });
          
          this.setData({
            list: list
          });
        } else {
          wx.showToast({
            title: res.data.msg || '加载失败',
            icon: 'none'
          });
        }
        
        if (callback) callback();
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        if (callback) callback();
      }
    });
  },

  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    const standard = this.data.list.find(item => item.id === id);
    
    wx.navigateTo({
      url: `/pages/quality-standard-detail/quality-standard-detail?id=${id}`,
      success: () => {
        // 传递标准数据
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        if (currentPage.setStandardData) {
          currentPage.setStandardData(standard);
        }
      }
    });
  },

  formatTime(timestamp) {
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
});
